package com.bjpowernode.controller;

import com.bjpowernode.model.TCustomer;
import com.bjpowernode.query.CustomerQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @PostMapping(value = "/api/clue/customer")
    public R convertCustomer(@RequestBody CustomerQuery customerQuery, @RequestHeader(value = "Authorization") String jwt) {
        customerQuery.setJwt(jwt);
        Boolean convert = customerService.convertCustomer(customerQuery);
        return convert ? R.OK() : R.FAIL();
    }
    @GetMapping(value = "/api/customer")
    public R customerPage(@RequestParam(value = "current") Integer current) {
        if (current == null) {
            current = 1;
        }

        PageInfo<TCustomer> pageInfo = customerService.getCustomerByPage(current);
        return R.OK(pageInfo);
    }
    @GetMapping(value = "/api/exportExcel")
    public R exportExcel(HttpServletResponse response,@RequestParam(value = "ids",required = false)String ids) throws IOException {
        //后端查询数据库的数据，把数据写入Excel，把Excel以流的方式返回给前端页面（我们实现）
        String excelFileName = URLEncoder.encode("客户信息数据"+System.currentTimeMillis(), "UTF-8");

        //设置响应内容类型

        response.setContentType("application/octet-stream");
        //设置响应头是附件(告诉浏览器，我给你返回的是文件啊，你要弹出框进行下载，而不是直接解析和渲染)
        response.setHeader("Content-disposition", "attachment;filename="+excelFileName+".xlsx");
        customerService.exportExcel(response.getOutputStream(),ids);
        return R.OK();
    }
    @GetMapping(value = "/api/customer/detail/{id}")
    public R customerDetail(@PathVariable(value = "id") Integer id) {
        TCustomer tCustomer = customerService.getCustomerById(id);
        return R.OK(tCustomer);
    }

}
